<template>
  <md-main>
    <el-collapse-transition>
      <div class="md-body mb20" v-show="showSearch">
        <el-form :model="search" ref="search" size="small" :inline="true">
          <el-form-item label="参数名称" prop="configName">
            <el-input v-model="search.configName" placeholder="请输入参数名称" clearable class="w150" />
          </el-form-item>
          <el-form-item label="参数键名" prop="configKey">
            <el-input v-model="search.configKey" placeholder="请输入参数键名" clearable class="w150" />
          </el-form-item>
          <el-form-item label="参数类型" prop="configType">
            <md-dict-select v-model="search.configType" :options="dictData['sys_config_type']" placeholder="系统内置" class="w150"></md-dict-select>
          </el-form-item>
          <!-- <el-form-item label="创建时间">
            <el-date-picker v-model="dateRange" class="w250" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item> -->
          <el-form-item>
            <md-button type="primary" icon="el-icon-search" @click="handleQuery()">搜索</md-button>
            <md-button icon="el-icon-refresh" @click="handleQueryReset()">重置</md-button>
          </el-form-item>
        </el-form>
      </div>
    </el-collapse-transition>

    <div class="md-body md-table">
      <md-toolbar>
        <md-button type="primary" size="small" plain :prems="['system:config:add']" @click="handleAdd()">新增</md-button>
        <md-button type="success" size="small" plain :prems="['system:config:remove']" :disabled="tableSelectIds.length===0" @click="handleDelete()">批量删除</md-button>

        <template slot="right">
          <md-button size="mini" icon="el-icon-search" circle @click="showSearch=!showSearch"></md-button>
          <md-button type="primary" size="mini" icon="el-icon-refresh" circle @click="getTableDataList()"></md-button>
        </template>
      </md-toolbar>

      <el-table v-loading="tableLoading" :data="tableData" @selection-change="handleTableSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="configId" />
        <el-table-column label="参数名称" align="center" prop="configName" width="200" show-overflow-tooltip />
        <el-table-column label="参数键名" align="center" prop="configKey" width="200" show-overflow-tooltip />
        <el-table-column label="参数键值" align="center" prop="configValue" width="200" show-overflow-tooltip />
        <el-table-column label="系统类型" align="center" prop="configType">
          <template slot-scope="{ row }">
            <md-dict-tag :options="dictData['sys_config_type']" :value="row.configType"></md-dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" width="200" show-overflow-tooltip />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
        <el-table-column label="操作" align="center" fixed="right" width="150px">
          <template slot-scope="{ row }">
            <md-button size="mini" type="text" icon="el-icon-edit" :prems="['system:config:edit']" @click="handleUpdate(row)">修改</md-button>
            <md-button size="mini" type="text" icon="el-icon-delete" :prems="['system:config:remove']" @click="handleDelete(row)">删除</md-button>
          </template>
        </el-table-column>
      </el-table>

      <md-pagination v-show="tableTotal>0" :total="tableTotal" :page.sync="search.pageIndex" :limit.sync="search.pageSize" @pagination="getTableDataList" />
    </div>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="dialog.title" :visible.sync="dialog.open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="request" :rules="rules" size="small" label-width="80px" label-position="right">
        <el-form-item label="参数名称" prop="configName">
          <el-input v-model="request.configName" :disabled="['C','S'].includes(request.configType)" placeholder="请输入参数名称" />
        </el-form-item>
        <el-form-item label="系统内置" prop="configType" v-if="request.configId===0">
          <md-dict-radio-group :options="dictData['sys_config_type']" radio="button" v-model="request.configType"></md-dict-radio-group>
        </el-form-item>
        <el-form-item label="参数键名" prop="configKey">
          <el-input v-model="request.configKey" :disabled="['C','S'].includes(request.configType)" placeholder="请输入参数键名" />
        </el-form-item>

        <!--系统内置-->
        <template v-if="request.configType==='Y'">
          <el-form-item label="参数键值" prop="configValue">
            <el-input type="textarea" :rows="5" v-model="request.configValue" placeholder="请输入参数键值" />
          </el-form-item>
        </template>
        <!--图片-->
        <template v-if="request.configType==='M'">
          <el-form-item label="参数键值" prop="configValue">
            <md-image-upload v-model="request.configValue" text="上传图片"></md-image-upload>
          </el-form-item>
        </template>
        <!--文件-->
        <template v-if="request.configType==='F'">
          <el-form-item label="参数键值" prop="configValue">
            <md-file-upload v-model="request.configValue" :size="10" :exts="['mp4','mp3','xls','xlsx','doc','docx', 'pdf', 'txt']" part></md-file-upload>
          </el-form-item>
        </template>
        <!--文本-->
        <template v-if="request.configType==='T'">
          <el-form-item label="参数键值" prop="configValue">
            <el-input type="textarea" :rows="5" v-model="request.configValue" placeholder="请输入参数键值" />
          </el-form-item>
        </template>
        <!--对象存储\短信-->
        <template v-if="['C','S'].includes(request.configType)">
          <el-form-item label="参数键值" prop="configValue">
            <div class="config-values" v-if="request.configValueFormList && request.configValueFormList.length>0">
              <el-row v-for="item in request.configValueFormList" :key="item.label" style="border-bottom: 1px solid #ececec;">
                <el-col :span="6">
                  {{item.label}}
                </el-col>
                <el-col :span="1">：</el-col>
                <el-col :span="15">
                  {{item.value}}
                </el-col>
              </el-row>
            </div>
          </el-form-item>
        </template>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="request.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="handleSubmit">确 定</el-button>
        <el-button size="small" @click="handleCancel">取 消</el-button>
      </div>
    </el-dialog>
  </md-main>
</template>

<style lang="less" scoped>
.config-values {
  .el-row {
    .el-col {
      ::v-deep .el-input {
        input {
          border: none !important;
        }
      }
    }
  }
}
</style>

<script>
import { insertConfig, updateConfig, listPageConfig, delConfig, getConfig } from '@/api/system/config.service.js'
import { mdGetDictData } from '@/ddd/dict.service.js'
export default {
  name: 'MdSystemConfigComponent',
  data () {
    return {
      // 显示隐藏查询条件
      showSearch: true,
      // 查询参数
      search: searchParams,
      // 列表加载
      tableLoading: false,
      // 列表数据
      tableData: [],
      // 列表数据，总条数
      tableTotal: 0,
      // 已选择的列表数据
      tableSelectIds: [],
      // 添加/编辑请求参数
      request: requestParams,
      rules: rules,
      // 添加/编辑弹窗
      dialog: {
        title: '添加参数',
        open: false
      },
      dictData: {}
    }
  },
  mounted () {
    mdGetDictData(['sys_config_type']).then(res => {
      this.dictData = res
    })

    this.getTableDataList()
  },
  methods: {
    /** 获取岗位数据 */
    async getTableDataList () {
      this.tableLoading = true
      this.tableData = []

      try {
        const res = await listPageConfig(this.search)

        const data = res.data.items
        if (data && data.length > 0) {
          data.forEach(item => {
            if (item.configValue && ['C', 'S'].includes(item.configType)) {
              item.configValueJson = JSON.parse(item.configValue)
              item.configValueKeys = Object.keys(item.configValueJson)
            }
          })
        }
        this.tableData = data
        this.tableTotal = res.data.totalItems
      } catch (error) {
        console.log(error)
      }

      this.tableLoading = false
    },
    /** 表格复选框事件 */
    handleTableSelectionChange (event) {
      this.tableSelectIds = event.map(m => { return m.configId })
    },
    /** 搜索 */
    handleQuery () {
      this.search.pageIndex = 1

      this.getTableDataList()
    },
    /** 重置搜索 */
    handleQueryReset () {
      this.search = { ...searchParams }

      this.getTableDataList()
    },
    // 重置表单数据
    handleReset () {
      this.request = { ...requestParams }
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    /** 删除岗位 */
    async handleDelete (row) {
      try {
        const ids = row?.configId || this.tableSelectIds

        await this.$confirm(`是否确认删除编号为${ids}的数据项？`)

        await delConfig(ids)

        this.$message.success('删除成功')

        this.handleQuery()
      } catch (error) {
        console.log(error)
      }
    },
    /** 添加岗位 */
    async handleAdd () {
      try {
        this.handleReset()

        this.dialog.title = '添加参数'

        this.dialog.open = true

        this.request = { ...requestParams }
      } catch (error) {
        console.log(error)
      }
    },
    /** 修改岗位 */
    async handleUpdate (row) {
      try {
        this.handleReset()

        const res = await getConfig(row.configId)

        const data = res.data

        if (data.configValue && ['C', 'S'].includes(data.configType)) {
          data.configValueJson = JSON.parse(data.configValue)
          data.configValueKeys = Object.keys(data.configValueJson)
          data.configValueFormList = []
          if (data.configValueKeys.length > 0) {
            data.configValueKeys.forEach(key => {
              const configValueFormItem = {
                label: key,
                value: data.configValueJson[key]
              }
              data.configValueFormList.push(configValueFormItem)
            })
          }
        }

        this.request = data

        this.dialog.open = true

        this.dialog.title = '修改参数'

      } catch (error) {
        console.log(error)
      }
    },
    /** 提交 */
    handleSubmit () {
      this.$refs.form.validate(async valid => {
        if (!valid) {
          return
        }

        try {
          const params = Object.assign({}, { ...this.request })

          await (params.configId === undefined ? insertConfig : updateConfig)(params)

          this.$message.success(params.configId === undefined ? '添加成功' : '修改成功')

          this.dialog.open = false;

          this.handleQuery()
        } catch (error) {
          console.log(error)
        }
      })
    },
    /** 取消 */
    handleCancel () {
      this.dialog.open = false

      this.handleReset()
    }
  }
}
const searchParams = {
  configName: undefined,
  configKey: undefined,
  configType: undefined,
  createBy: undefined,
  updateBy: undefined,
  beginDate: undefined,
  endDate: undefined,
  orderBy: 'create_time',
  isDesc: true,
  pageIndex: 1,
  pageSize: 10
}

const requestParams = {
  configId: undefined,
  configName: undefined,
  configKey: undefined,
  configValue: undefined,
  configType: 'Y',
  remark: undefined
}

const rules = {
  configName: [{ required: true, message: '请输入参数名称', trigger: 'blur' }],
  configKey: [{ required: true, message: '请输入参数键名', trigger: 'blur' }],
  configValue: [{ required: true, message: '请输入参数键值', trigger: 'blur' }]
}
</script>